<template>
  <div class="addBpm">
    <Form :model="bpmModel" ref="approvalForm" :rules="ruleValidate" :label-width="180">
      <Col span="20">
        <Form-item label="流程名称" prop="name">
          <Input type="text" v-model="bpmModel.name" placeholder="请输入流程名称" :disabled="readOnly"></Input>
        </Form-item>
      </Col>
      <Col span="20" v-if="!readOnly">
        <Form-item label="评分轮数" prop="round">
          <Select size="default" v-model="bpmModel.round">
            <Option v-for="item in moduleOptions" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Form-item>
      </Col>
      <Col span="20">
        <Form-item label="是否对系统已有表单评分" prop="isSystemInside">
          <div slot="label" style="display: inline-flex;">
            <div>是否对系统已有表单评分</div>
            <Tooltip
              transfer
              max-width="800"
              content="是否对系统已有的表单进行评分，比如AI大赛表、标杆申报表。"
              placement="right"
              slot
            >
              <Icon type="ios-help-circle-outline" />
            </Tooltip>
          </div>
          <RadioGroup v-model="bpmModel.isSystemInside" @on-change="onSystemInsideChange">
            <Radio label="true" :disabled="readOnly">是</Radio>
            <Radio label="false" :disabled="readOnly">否</Radio>
          </RadioGroup>
        </Form-item>
      </Col>
      <Col span="20">
        <Form-item label="是否多人协同编辑" prop="isShared">
          <div slot="label" style="display: inline-flex;">
            <div>是否多人协同编辑</div>
            <Tooltip
              transfer
              max-width="800"
              content="多人协同编辑是指多个用户填写同一张表单，即每个用户填写表单中的不同评分指标。"
              placement="right"
              slot
            >
              <Icon type="ios-help-circle-outline" />
            </Tooltip>
          </div>
          <RadioGroup v-model="bpmModel.isShared" :disabled="readOnly">
            <Radio label="true" :disabled="readOnly">是</Radio>
            <Radio label="false" :disabled="readOnly">否</Radio>
          </RadioGroup>
        </Form-item>
      </Col>
      <Col span="20">
        <Form-item label="配置评分用户" label-position="top">
          <Table :columns="approveColumns" :data="tableData" border></Table>
          <div style="text-align: end;" v-if="!readOnly">
            <RPButton
              type="button"
              optType="create"
              text="新增"
              html-type="button"
              style="width:100%"
              icon="md-add"
              @click="addRow"
            />
          </div>
        </Form-item>
      </Col>

      <Row :gutter="10">
        <Col span="20">
          <Form-item label="备注" prop="remark">
            <Input
              type="textarea"
              :rows="4"
              v-model="bpmModel.remark"
              placeholder="请输入备注"
              :disabled="readOnly"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="10" v-if="showForms">
        <Col span="20">
          <Form-item label="已关联表单" prop="formList">
            <Tag
              type="border"
              v-for="item in bpmModel.formList"
              :key="item.id"
              :name="item"
              :closable="tagcClosable(item)"
              @on-close="handleClose"
              >{{ item.name }}</Tag
            >
          </Form-item>
        </Col>
      </Row>
    </Form>
  </div>
</template>

<script>
import SelectUserPage from './components/SelectUser.vue'
import SelectRate from './components/SelectRate.vue'
import bpmpCenterApi from '@/api/bpmCenter.js'
import { mapState } from 'vuex'
import {
  STATUS_TYPE_DRAFT,
  STATUS_TYPE_PENDING,
  STATUS_TYPE_REVIEW,
  STATUS_TYPE_APPROVED,
  STATUS_TYPE_REJECTED,
  STATUS_TYPE_FINISH
} from '@/views/formConst'
export default {
  components: {},
  data() {
    return {
      showForms: false,
      bpmModel: {
        round: 1,
        year: new Date().getFullYear(),
        formType: 3,
        name: '',
        isShared: 'false',
        isSystemInside: 'true',
        remark: '',
        formIdList: [],
        formList: [],
        config: ''
      },
      ruleValidate: {
        name: [{ required: true, message: '请填写流程名称', trigger: 'blur' }]
        // formList: [{ required: true, type: 'array', message: '请选择关联表单', trigger: 'blur' }]
      },
      moduleOptions: [
        { label: '1', value: 1 },
        { label: '2', value: 2 },
        { label: '3', value: 3 }
      ],
      config: {
        configGroups: [
          {
            evaluationTarget: {},
            submitter: {},
            approver: {},
            vars: {
              submitter1: '',
              submitter2: '',
              submitter3: ''
            }
          }
        ]
      },
      tableData: [
        {
          fill: [],
          submitter1: [],
          submitter2: [],
          submitter3: []
        }
      ],
      flatOrg: [],
      orgDatas: [],
      loading: false,
      actions: [
        {
          text: '提交',
          theme: 'primary',
          handle: () => {
            if (this.isEmptytableData()) {
              return
            }
            this.$refs['approvalForm']
              .validate(valid => {
                if (valid) {
                  const config = this.tableData2Config(this.config)
                  this.loading = true
                  bpmpCenterApi.bpmpSubmit({ ...this.bpmModel, config }).then(res => {
                    this.loading = false
                    if (res.data.code == 200) {
                      this.$Message.success({
                        content: '新增成功',
                        duration: 3
                      })
                      this.id = res.data.data
                      this.initDataById()
                    }
                  })
                }
              })
              .catch(e => {
                this.loading = false
              })
          },
          loading: this.loading
        },
        {
          text: '暂存',
          theme: 'primary',
          handle: () => {
            const config = this.tableData2Config(this.config)
            this.loading = true
            bpmpCenterApi
              .bpmpSaveOrUpdate({ ...this.bpmModel, config })
              .then(res => {
                this.loading = false
                if (res.data.code == 200) {
                  this.$Message.success({
                    content: '暂存成功',
                    duration: 3
                  })
                  this.id = res.data.data
                  this.initDataById()
                }
              })
              .catch(e => {
                this.loading = false
              })
          },
          loading: this.loading
        },
        {
          text: this.$t('common.close'),
          handle: () => {
            this.$emit('Close')
          }
        }
      ],
      readActions: [
        {
          text: this.$t('common.close'),
          handle: () => {
            this.$emit('Close')
          }
        }
      ],
      readOnly: true
    }
  },
  computed: {
    ...mapState(['orgList']),
    approveColumns() {
      const list = [
        {
          title: '被评分对象',
          render: this.fillRender('fill')
        },
        {
          title: '第1轮评分',
          render: this.submitterRender('submitter1')
        },
        {
          title: '第2轮评分',
          render: this.submitterRender('submitter2')
        },
        {
          title: '第3轮评分',
          render: this.submitterRender('submitter3')
        },
        {
          title: '操作',
          align: 'left',
          fixed: 'right',
          width: 160,
          render: (h, params) => {
            return h('RowTools', {
              props: {
                data: [
                  {
                    type: 'text',
                    text: '删除',
                    hidden: this.readOnly,
                    handle: () => {
                      this.deleteRow(params.index)
                    }
                  }
                ]
              }
            })
          }
        }
      ]
      if (this.bpmModel.round < 3) {
        list.splice(this.bpmModel.round + 1, 3 - this.bpmModel.round)
      }
      if (this.bpmModel.isSystemInside === 'false') {
        list.shift()
      }
      if (this.readOnly) {
        list.pop()
      }
      return list
    }
  },
  props: {
    id: {
      type: String,
      default: ''
    },
    formId: {
      type: String,
      default: ''
    }
  },
  watch: {
    orgList(newValue, oldValue) {
      this.orgDatas = newValue
    },
    orgDatas(newValue, oldValue) {
      this.flatOrg = this.treeToFlat(newValue)
    }
  },
  mounted() {
    if (this.orgList.length <= 0) {
      this.$store.dispatch('getOrgList')
    } else {
      this.orgDatas = this.orgList
    }
    if (this.id) {
      this.initDataById()
    } else {
      this.readOnly = false
      this.$emit('SetTitle', '新建流程')
      this.$emit('SetPageActions', this.actions)
    }
  },
  methods: {
    initDataById() {
      bpmpCenterApi.bpmpGetById({ id: this.id }).then(res => {
        this.bpmModel = res.data
        this.bpmModel.isShared = String(this.bpmModel.isShared)
        this.bpmModel.isSystemInside = String(this.bpmModel.isSystemInside)
        if (this.bpmModel.status == STATUS_TYPE_FINISH) {
          this.readOnly = true
          this.showForms = true
          this.$emit('SetTitle', '查看流程')
          this.$emit('SetPageActions', this.readActions)
          //关联表单移到列表页
        } else {
          this.readOnly = false
          this.$emit('SetTitle', '编辑流程')
          this.$emit('SetPageActions', this.actions)
        }
        this.bpmModel.formIdList = this.bpmModel.formList.map(item => item.id)
        this.config2tableData(res.data.config)
      })
    },
    treeToFlat(tree, parentId = null) {
      let flat = []
      for (let node of tree) {
        let copy = { ...node, parentId }
        flat.push(copy)
        if (node.children && node.children.length > 0) {
          flat = flat.concat(this.treeToFlat(node.children, node.id))
        }
      }
      return flat
    },
    uniqueByKey(arr, key) {
      const seen = new Set()
      return arr.filter(item => {
        const serializedKey = JSON.stringify(item[key])
        return seen.has(serializedKey) ? false : seen.add(serializedKey)
      })
    },
    tagcClosable(item) {
      if (![STATUS_TYPE_APPROVED, STATUS_TYPE_FINISH].includes(Number(item.status))) {
        return false
      } else {
        if (this.formId) {
          if (item.id == this.formId) {
            return true
          } else {
            return false
          }
        } else {
          return true
        }
      }
    },
    handleClose(event, form) {
      this.$confirm({
        title: '解绑表单',
        content: '您是否要继续解绑表单?'
      }).then(res => {
        bpmpCenterApi
          .bpmpAssociate({
            bpmpId: this.id,
            formId: form.id
          })
          .then(res => {
            if (res.data.code == 200) {
              this.$Message.success({
                content: '解绑成功',
                duration: 3
              })
              this.initDataById()
            } else {
              this.$Message.error({
                content: res.data.msg || '关联失败',
                duration: 3
              })
            }
          })
      })
    },
    isEmptytableData() {
      let fillEmpty = 0
      let approveEmpty = 0
      this.tableData.forEach(item => {
        if (item.fill.length == 0) {
          fillEmpty = fillEmpty + 1
        }
        if (this.bpmModel.round == 1) {
          if (item.submitter1.length == 0) {
            approveEmpty = approveEmpty + 1
          }
        } else if (this.bpmModel.round == 2) {
          if (item.submitter1.length == 0 || item.submitter2.length == 0) {
            approveEmpty = approveEmpty + 1
          }
        } else if (this.bpmModel.round == 3) {
          if (item.submitter1.length == 0 || item.submitter2.length == 0 || item.submitter3.length == 0) {
            approveEmpty = approveEmpty + 1
          }
        }
      })
      if (this.bpmModel.isSystemInside === 'true' && fillEmpty > 0) {
        this.$Message.error({
          content: '请添加被评分对象',
          duration: 3
        })
        return true
      } else if (approveEmpty > 0) {
        this.$Message.error({
          content: '请添加评分人',
          duration: 3
        })
        return true
      }
      return false
    },
    onSystemInsideChange(value) {
      if (value === 'false') {
        //选择了非系统中的表
        this.$confirm({
          title: '对系统外表单评分',
          content: '无法在系统中选择被评分对象，您是否要继续?'
        })
          .then(res => {
            this.tableData.forEach(item => {
              item.fill = []
            })
          })
          .catch(() => {
            this.bpmModel.isSystemInside = 'true'
          })
      } else {
        // 选择了非系统中的表
        this.$confirm({
          title: '对系统中表单评分',
          content: '可选择系统中的被评分对象，您是否要继续?'
        })
          .then(res => {})
          .catch(() => {
            this.bpmModel.isSystemInside = 'false'
          })
      }
    },
    cancel() {
      this.$emit('Close')
    },
    tableData2Config(config) {
      let copyConfig = JSON.parse(JSON.stringify(config))
      copyConfig.configGroups = []
      this.tableData.forEach(item => {
        let configGroup = { evaluationTarget: {}, submitter: {}, vars: {} }

        item.fill.forEach(item => {
          configGroup.evaluationTarget[item.id] = item
        })

        Object.keys(item).forEach(key => {
          if (key.startsWith('submitter')) {
            const submitter = []
            item[key].forEach(user => {
              submitter.push(user.userId)
              configGroup.submitter[user.userId] = user
            })
            configGroup.vars[key] = submitter.join(' ')
          }
        })
        copyConfig.configGroups.push(configGroup)
      })
      return JSON.stringify(copyConfig)
    },
    config2tableData(networkData) {
      this.config = JSON.parse(networkData)
      this.tableData = []
      this.config.configGroups.forEach(item => {
        let data = { fill: [], submitter1: [], submitter2: [], submitter3: [] }

        Object.keys(item.evaluationTarget).forEach(key => {
          data.fill.push(item.evaluationTarget[key])
        })

        Object.keys(item.vars).forEach(key => {
          item.vars[key].split(' ').forEach(userId => {
            if (userId) {
              data[key].push(item.submitter[userId])
            }
          })
        })
        this.tableData.push(data)
      })
    },
    fillRender(key, refSelectUser, limit) {
      return (h, params) => {
        let arr = params.row[key] || []
        let renderArray = arr.map((item, index) => {
          return h('div', [
            h(
              'Tag',
              {
                props: {
                  type: 'border',
                  closable: !this.readOnly
                },
                style: {
                  display: 'flex',
                  overflow: 'hidden',
                  'justify-content': 'space-between',
                  'align-items': 'center',
                  'flex-wrap': 'nowrap'
                },
                on: {
                  'on-close': () => {
                    this.tableData[params.index][key].splice(index, 1)
                  }
                }
              },
              item['title']
            )
          ])
        })

        if (!this.readOnly && (!limit || arr.length < limit)) {
          renderArray.push(
            h('RPButton', {
              attrs: {
                icon: 'md-add',
                size: 'small',
                text: '选择表单'
              },
              props: {
                optType: 'create'
              },
              on: {
                click: () => {
                  new this.$pageModal(
                    SelectRate,
                    {
                      props: { orgDatas: this.orgDatas }
                    },
                    data => {
                      if (data) {
                        this.tableData[params.index][key].push(...data)
                        this.tableData[params.index][key] = this.uniqueByKey(this.tableData[params.index][key], 'id')
                      }
                    }
                  )
                }
              }
            })
          )
        }
        return h('div', renderArray)
      }
    },
    submitterRender(key, refSelectUser, limit) {
      return (h, params) => {
        let arr = params.row[key] || []
        let renderArray = [
          arr.map((item, index) => {
            return h(
              'Tag',
              {
                props: {
                  type: 'border',
                  closable: !this.readOnly
                },
                on: {
                  'on-close': () => {
                    this.tableData[params.index][key].splice(index, 1)
                  }
                }
              },
              item['userName']
            )
          })
        ]
        if (!this.readOnly && (!limit || arr.length < limit)) {
          renderArray.push(
            h('RPButton', {
              attrs: {
                icon: 'md-add',
                size: 'small',
                text: '添加'
              },
              props: {
                optType: 'create'
              },
              on: {
                click: () => {
                  new this.$pageModal(
                    SelectUserPage,
                    {
                      props: { orgDatas: this.orgDatas }
                    },
                    data => {
                      if (data) {
                        const approver = this.tableData[params.index]
                        let hasRepeat = false
                        Object.keys(approver).forEach(key => {
                          if (key.startsWith('approver') && !hasRepeat) {
                            data.forEach(user => {
                              let repeat = approver[key].find(item => item.userId == user.userId)
                              if (repeat) {
                                hasRepeat = true
                              }
                            })
                          }
                        })
                        if (hasRepeat) {
                          this.$Message.error({
                            content: `人员重复，添加失败`,
                            duration: 3
                          })
                        } else {
                          this.tableData[params.index][key].push(...data)
                        }
                      }
                    }
                  )
                }
              }
            })
          )
        }
        return h('div', renderArray)
      }
    },
    addRow() {
      const [last] = this.tableData.slice(-1)
      let newRow = JSON.parse(JSON.stringify(last))
      newRow.fill = []
      this.tableData.push(newRow)
    },
    deleteRow(index) {
      if (this.tableData.length == 1) {
        this.$Message.error({
          content: '请至少保留一行',
          duration: 3
        })
      } else {
        this.tableData.splice(index, 1)
      }
    },
    dealOrgPath(orgPath) {
      return orgPath.substring(orgPath.indexOf('/'))
    }
  }
}
</script>

<style lang="less" scoped>
.addBpm {
  margin-top: 20px;
}
/deep/ .ivu-tag-text {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
